< previous page page_524 next page >

Page 524
Notice that the syntax for adding multicolumn foreign key constraints differs from that used when creating single-column foreign key relationships. When creating multicolumn foreign key relationships, you have to actually use the keywords FOREIGN KEY. Also, you list the columns in parentheses in the same order in which they are listed in the referenced key for the referenced table.
Using ALTER TABLE to ADD and DROP Constraints
You can also use the ALTER TABLE statement to add constraints or drop constraints from existing data tables. The code example in Listing 13.16 adds a new constraint to an existing table, and then removes it. You should be careful adding or dropping constraints outside of the CREATE TABLE statement. Although SQL allows you to do this, it can often lead to data integrity errors if data already exists within the target table. We recommend that you only establish CONSTRAINTs at the time you create the table using the CREATE TABLE statement.
Type.gifListing 13.16. Using ALTER TABLE to ADD and DROP constraints.
// create a database
dbMake sqlvb04.mdb;
// create budget tracking file
CREATE TABLE BudgetTrack
   (BudgetPrefix TEXT(5),
    BudgetCode   TEXT(10),
    BudgetSuffix TEXT(5),
    CONSTRAINT PKBudgetCode PRIMARY KEY (BudgetPrefix,BudgetCode,BudgetSuffix),
    AnnBudgetAmt CURRENCY,
    YTDActualAmt CURRENCY
   );
// create jobs title table
CREATE TABLE JobsTable
   (JobTitle TEXT (20) CONSTRAINT PKJobTitle PRIMARY KEY,
    BudgetPrefix TEXT(5),
    BudgetCode   TEXT(10),
    BudgetSuffix TEXT(5),
    JobDesc MEMO,
    CONSTRAINT FKBudget
       FOREIGN KEY (BudgetPrefix,BudgetCode,BudgetSuffix)
       REFERENCES  BudgetTrack
   );
// create job pay grade table
CREATE TABLE PayGrades
   (GradeID  TEXT(5)  CONSTRAINT PKGradeID PRIMARY KEY,
    JobName  TEXT(20) CONSTRAINT FKJobName REFERENCES JobsTable(JobTitle),
    PayMin   CURRENCY,
    PayMax   CURRENCY
   );
// create a test table to work with
CREATE TABLE EmpsTable

 
< previous page page_524 next page >

If you like this book, buy it!